package com.lc.activiti.sys.controller;


import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.lc.activiti.sys.entity.SysFile;
import com.lc.activiti.sys.service.SysFileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * (SysFile)表控制层
 *
 * @author 骆超
 * @since 2021-07-19 16:09:04
 */
@RestController
@RequestMapping("sysFile")
public class SysFileController {
    /**
     * 服务对象
     */
    @Resource
    private SysFileService sysFileService;

    @Value("${filePath}")
    private String filePath;

    /**
     * 文件上传
     * @author 骆超
     * @date 2021/7/19
     * @param multipartFile 参数说明
     */
    @RequestMapping("uploadImg")
    @ResponseBody
    public SysFile uploadImg(@RequestParam(value="img",required=false) MultipartFile multipartFile) throws IOException {
        //获取文件名（包含拓展名）
        String filename= multipartFile.getOriginalFilename();
        //获取文件名称
        assert filename != null;
        String suffix= filename.substring(filename.lastIndexOf("."));
        String folder = filePath+DateUtil.format(DateUtil.date(), DatePattern.NORM_DATE_PATTERN);
        String saveName = IdUtil.randomUUID()+suffix;
        String fileUrl = folder+File.separator+saveName;
        File file =new File(fileUrl);
        FileUtil.touch(file);
        //将上传的文件写入至目标文件
       multipartFile.transferTo(file);
       SysFile sysFile = new SysFile().setFileName(saveName).setFizeSize(multipartFile.getSize()).setFolder(folder).setSuffix(suffix);
       sysFile.insertOrUpdate();
       return sysFile;
    }

    @PostMapping("getFileById")
    public String getFileById(@RequestBody SysFile sysFile,HttpServletResponse response) throws IOException {
        if (ObjectUtil.isNotEmpty(sysFile.getId())){
            sysFile = sysFileService.getById(sysFile);
            byte[] bytes = FileUtil.readBytes(sysFile.getFolder() +File.separator+ sysFile.getFileName());
            return  "data:image/jpeg;base64,"+Base64.encode(bytes);
        }else{
            return null;
        }
    }

}
